package com.gitee.feizns.data.impl;

import com.gitee.feizns.data.MetaData;
import com.gitee.feizns.data.Table;
import lombok.SneakyThrows;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * @author feizns
 * @since 2019/7/6 0006
 */
public class MetaDataImpl implements MetaData {

    /**
     * url
     */
    private String url;

    /**
     * 用户名
     */
    private String username;

    /**
     * 密码
     */
    private String pwd;

    /**
     * 驱动类名称
     */
    private String driverClassName;

    /**
     * 数据库连接
     */
    private Connection connection;

    /**
     * 数据库信息
     */
    private DatabaseMetaData databaseMetaData;

    public MetaDataImpl(String url, String username, String pwd, String driverClassName) {
        this.url = url;
        this.username = username;
        this.pwd = pwd;
        this.driverClassName = driverClassName;

        init();
    }

    @SneakyThrows
    private void init() {
        Class.forName(driverClassName);
        this.connection = DriverManager.getConnection(url, username, pwd);
        this.databaseMetaData = connection.getMetaData();
    }

    @SneakyThrows
    @Override
    public List<Table> getTables() {
        List<Table> ret = new ArrayList<>();

        ResultSet tables = databaseMetaData.getTables(null, "%", "%", new String[]{"TABLE", "REMARKS"});

        while ( tables.next() ){
            ret.add(new TableImpl(tables.getString("TABLE_NAME"), databaseMetaData));
        }

        return ret;
    }

    @Override
    public void close() throws Exception {
        if ( connection != null )
            connection.close();
    }

}
